package net.xdclass.service.impl;

import lombok.extern.slf4j.Slf4j;
import net.xdclass.controller.request.AccoountRegisterRequest;
import net.xdclass.controller.request.AccountLoginRequest;
import net.xdclass.enums.AuthTypeEnum;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.enums.SendCodeEnum;
import net.xdclass.manager.AccountManager;
import net.xdclass.model.AccountDO;
import net.xdclass.model.LoginUser;
import net.xdclass.service.AccountService;
import net.xdclass.service.NotifyService;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.IDUtil;
import net.xdclass.util.JWTUtil;
import net.xdclass.util.JsonData;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jcajce.provider.digest.MD5;
import org.junit.jupiter.api.AfterEach;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 小滴课堂,愿景：让技术不再难学
 *
 * @Description
 * @Author 二当家小D
 * @Remark 有问题直接联系我，源码-笔记-技术交流群
 * @Version 1.0
 **/

@Service
@Slf4j
public class AccountServiceImpl implements AccountService {
    @Autowired
    private NotifyService notifyService;
    @Autowired
    private AccountManager accountManager;
    /**
     * 手机验证码验证
     * 密码加密(TODO)√
     * 账号唯一性检查(TODO)数据库唯一索引
     * 插入数据库
     * 新注册用户福利发放(TODO)
     * @param request
     * @return
     */
    @Override
    public JsonData register(AccoountRegisterRequest request) {

        boolean checkCode = false;
        if(StringUtils.isNotBlank(request.getPhone())){
            checkCode = notifyService.checkCode(SendCodeEnum.USER_REGISTER, request.getPhone(), request.getCode());
        }
        //验证码错误
        if(!checkCode){
            return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
        }
        AccountDO accountDO = new AccountDO();
        BeanUtils.copyProperties(request,accountDO);
        accountDO.setAuth(AuthTypeEnum.DEFAULT.name());
        /**
         * 密码加密
         * 盐
         */
        accountDO.setSecret("$1$"+ CommonUtil.getStringNumRandom(8));
        String crypPwd = Md5Crypt.md5Crypt(request.getPwd().getBytes(), accountDO.getSecret());
        accountDO.setPwd(crypPwd);
        //TODO后面改动√
        accountDO.setAccountNo(Long.valueOf(IDUtil.geneSnowFlakeID().toString()));

        int rows = accountManager.insert(accountDO);
        log.info("注册成功，影响行数：{}",rows);
        //注册成功发放福利
        userRegisterInitTask(accountDO);


        return JsonData.buildSuccess();
    }

    /**
     * 登录
     * 1.根据手机号查询
     * 2.把数据库中的盐取出，与输入的密码加密得到密文
     * 3.对比数据库中的密文是否一致
     * @param request
     * @return
     */
    @Override
    public JsonData login(AccountLoginRequest request) {
        List<AccountDO> accountDOList = accountManager.findByPhone(request.getPhone());
        if(accountDOList != null && accountDOList.size()==1){
            AccountDO accountDO = accountDOList.get(0);
            String secret = accountDO.getSecret();
            String md5Crypt = Md5Crypt.md5Crypt(request.getPwd().getBytes(), secret);
            if(md5Crypt.equals(accountDO.getPwd())){
                LoginUser loginUser = LoginUser.builder().build();
                BeanUtils.copyProperties(accountDO,loginUser);
                //生成TOKEN
                String token = JWTUtil.geneJsonWebToken(loginUser);
                return JsonData.buildSuccess(token);
            }else {
                return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNREGISTER);
            }
        }else {
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNREGISTER);
        }

    }

    /**
     * TODO注册成功发放福利
     */
    private void userRegisterInitTask(AccountDO accountDO) {
    }
}
